from typing import Dict, List, Optional
import ccxt
import pandas as pd
from datetime import datetime
from .base_exchange import BaseExchange

class OKXExchange(BaseExchange):
    """OKX交易所实现"""
    
    def initialize(self):
        """初始化OKX交易所连接"""
        try:
            self.exchange = ccxt.okx({
                'apiKey': self.api_key,
                'secret': self.api_secret,
                'enableRateLimit': True,
                'options': {
                    'defaultType': 'spot',  # 现货交易
                }
            })
            return True
        except Exception as e:
            self.handle_error(e)
            return False
            
    def get_balance(self) -> Dict:
        """获取账户余额"""
        try:
            balance = self.exchange.fetch_balance()
            return {
                'total': balance['total'],
                'free': balance['free'],
                'used': balance['used']
            }
        except Exception as e:
            return self.handle_error(e)
            
    def get_ticker(self, symbol: str) -> Dict:
        """获取最新行情"""
        try:
            ticker = self.exchange.fetch_ticker(symbol)
            return {
                'symbol': symbol,
                'bid': ticker['bid'],
                'ask': ticker['ask'],
                'last': ticker['last'],
                'volume': ticker['baseVolume'],
                'timestamp': ticker['timestamp']
            }
        except Exception as e:
            return self.handle_error(e)
            
    def get_orderbook(self, symbol: str, limit: int = 20) -> Dict:
        """获取订单簿"""
        try:
            orderbook = self.exchange.fetch_order_book(symbol, limit)
            return {
                'symbol': symbol,
                'bids': orderbook['bids'],
                'asks': orderbook['asks'],
                'timestamp': orderbook['timestamp']
            }
        except Exception as e:
            return self.handle_error(e)
            
    def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> pd.DataFrame:
        """获取K线数据"""
        try:
            ohlcv = self.exchange.fetch_ohlcv(symbol, timeframe, limit=limit)
            return self.format_ohlcv(ohlcv)
        except Exception as e:
            return self.handle_error(e)
            
    def create_order(self, symbol: str, order_type: str, side: str,
                    amount: float, price: Optional[float] = None) -> Dict:
        """创建订单"""
        try:
            order = self.exchange.create_order(
                symbol,
                order_type,
                side,
                amount,
                price
            )
            return {
                'id': order['id'],
                'symbol': order['symbol'],
                'type': order['type'],
                'side': order['side'],
                'amount': order['amount'],
                'price': order['price'],
                'status': order['status']
            }
        except Exception as e:
            return self.handle_error(e)
            
    def cancel_order(self, order_id: str, symbol: str) -> bool:
        """取消订单"""
        try:
            self.exchange.cancel_order(order_id, symbol)
            return True
        except Exception as e:
            self.handle_error(e)
            return False
            
    def get_open_orders(self, symbol: str = None) -> List[Dict]:
        """获取未完成订单"""
        try:
            orders = self.exchange.fetch_open_orders(symbol)
            return [{
                'id': order['id'],
                'symbol': order['symbol'],
                'type': order['type'],
                'side': order['side'],
                'amount': order['amount'],
                'price': order['price'],
                'status': order['status']
            } for order in orders]
        except Exception as e:
            return self.handle_error(e)
            
    def get_order_status(self, order_id: str, symbol: str) -> Dict:
        """获取订单状态"""
        try:
            order = self.exchange.fetch_order(order_id, symbol)
            return {
                'id': order['id'],
                'status': order['status'],
                'filled': order['filled'],
                'remaining': order['remaining'],
                'average': order['average']
            }
        except Exception as e:
            return self.handle_error(e)
            
    def get_position(self, symbol: str) -> Dict:
        """获取持仓信息"""
        try:
            positions = self.exchange.fetch_positions([symbol])
            if positions and len(positions) > 0:
                pos = positions[0]
                return {
                    'symbol': pos['symbol'],
                    'size': pos['contracts'],
                    'side': pos['side'],
                    'entry_price': pos['entryPrice'],
                    'leverage': pos['leverage'],
                    'unrealized_pnl': pos['unrealizedPnl']
                }
            return None
        except Exception as e:
            return self.handle_error(e)
